<template>
  <el-cascader
    ref="areaCascader"
    v-model="areaCodeModel"
    clearable
    filterable
    style="width:100%"
    :options="areaData"
    :props="areaProps"
    :disabled="isDisabled"
    @change="handleArea"
  />
</template>

<script>
import { commonArea } from '@/api/common';
export default {
  props: {
    isDisabled: {
      type: Boolean,
      default: false
    },
    areaCode: {
      type: [String, Array],
      default: () => {
        return [];
      }
    }
  },
  data() {
    return {
      areaData: [],
      areaProps: {
        value: 'code',
        label: 'name',
        children: 'children',
        expandTrigger: 'hover',
        checkStrictly: true
      }
    };
  },
  computed: {
    areaCodeModel: {
      get() {
        return this.areaCode;
      },
      set(v) {
        this.$emit('update:areaCode', v); // :areaCode.sync=""
      }
    }
  },
  created() {
    this.getAreaData();
  },
  methods: {
    getAreaData() {
      const areaData = window.areaData;
      if (areaData) {
        this.areaData = areaData;
      } else {
        commonArea({
          areaCode: '33050000', // 地区编码 如果type选2 则此字段传00000000-只有省级(),如果传省级code:33000000(则显示市-区-街道)
          type: '1' // 地区类型 1-宁波/湖州 2-全国 (不传默认为2)
        }).then(({ value, success }) => {
          if (success && value) {
            this.areaData = value;
            window.commonAreaData = value;
          }
        });
      }
    },
    handleReset(data = []) { // 重置,父组件清空调用
      this.areaCodeModel = data;
    },
    handleArea(e) {
      this.$refs.areaCascader.dropDownVisible = false;
      const nodes = this.$refs.areaCascader.getCheckedNodes()[0];
      const label = nodes?.pathLabels;
      this.$emit('handleArea', { value: e[e.length - 1], label });
    }
  }
};
</script>

<style lang="scss">
.el-cascader-panel .el-radio {
  width: 100%;
  height: 100%;
  z-index: 10;
  position: absolute;
  top: 10px;
  right: 10px;
}

.el-cascader-panel .el-radio__input {
  visibility: hidden;
}

.el-cascader-panel .el-cascader-node__postfix {
  top: 10px;
}
</style>
